class ReviewsController < ApplicationController
  # Require authentication for edit and delete.
  before_filter :authorize
	
	# GET /reviews
  # GET /reviews.xml
  def index
    @reviews = Review.all
		@movie = Movie.find(params[:movie_id])
		
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @reviews }
    end
  end

  # GET /reviews/1
  # GET /reviews/1.xml
  def show
    @review = Review.find(params[:id])
		@movie = Movie.find(params[:movie_id])
		
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @review }
    end
  end

  # GET /reviews/new
  # GET /reviews/new.xml
  def new
    @review = Review.new
		@movie = Movie.find(params[:movie_id])

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @review }
    end
  end

  # GET /reviews/1/edit
  def edit
		@movie = Movie.find(params[:movie_id])
    @review = Review.find(params[:id])
  end

  # POST /reviews
  # POST /reviews.xml
  def create
		# movie_id because of nested route
		@movie = Movie.find(params[:movie_id])
		#@user = User.find_by_id(session[:user_id])
		# build sets the movie_id foreign key automatically
		@review = @movie.reviews.build(params[:review])
		#@review = Review.new(params[:review])
		@review.user_id = current_user.id
    #@review.movie_id = params[:movie_id]

		if @review.save
			flash[:notice] = 'Review successfully created.'
			redirect_to(movie_review_path(@movie, @review))
		else
			render :action => "new"
		end

	end
 

  # PUT /reviews/1
  # PUT /reviews/1.xml
  def update
		@movie = Movie.find(params[:movie_id])
    @review = Review.find(params[:id])

    respond_to do |format|
      if @review.update_attributes(params[:review])
        flash[:notice] = 'Review was successfully updated.'
        format.html { redirect_to(movie_review_path(@movie,@review)) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @review.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /reviews/1
  # DELETE /reviews/1.xml
  def destroy
		@movie = Movie.find(params[:movie_id])
    @review = Review.find(params[:id])
    @review.destroy

    respond_to do |format|
      format.html { redirect_to(reviews_url) }
      format.xml  { head :ok }
    end
  end
end
